package com.neusiri.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.neusiri.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * SmsUtil
 * 短信工具类
 *
 * @author 丛有志
 * @date 2020/11/12 20:20
 * <p>
 * 版本        修改时间        作者        修改内容
 * V1.0        2020/11/12     丛有志        初始版本
 */
@Slf4j
@Component
public class SmsUtil {

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessKeySecret}")
    public String secret;

    @Value("${aliyun.sms.template_code}")
    private String templateCode;

    /**
     * 定义短信发送成功状态
     */
    String smsSendSuccessStatus = "OK";

    /**
     * 定义短信发送回参
     */
    CommonResponse response = new CommonResponse();

    public boolean sendPicCode(String phoneNumber, String picCode) {
        // 定义Map用于存短信模板中参数
        Map<String, String> templateParamMap = new HashMap<>(16);
        templateParamMap.put("code", picCode);
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        // 阿里云短信服务版本不可个修改
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        // 设置签名-[注]当签名为中文时,写在配置文件中读取后可能乱码,乱码会导致短信发不出
        request.putQueryParameter("SignName", "rabbitmq短信服务");
        request.putQueryParameter("TemplateCode", templateCode);

        // 短信模板中信息
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(templateParamMap));
        try {
            response = client.getCommonResponse(request);
        } catch (ClientException e) {
            log.error("验证码发送错误：{}", e.getLocalizedMessage());
            throw new BusinessException(4004, "短信发送错误");
        }
        JSONObject jsonObject = JSON.parseObject(response.getData());
        return smsSendSuccessStatus.equals(jsonObject.get("Message"));
    }
}
